﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Mbs.Collections
{
    public static class CollectionExtensions
    {
        public static bool Exists<T>(this IQueryable<T> queryable)
        {
            return queryable.Count() != 0;
        }

        public static bool TrueForAll<T>(this IEnumerable<T> coll, Predicate<T> predicate)
        {
            Trace.Assert(coll != null, "coll == null");
            Trace.Assert(predicate != null, "predicate == null");

            var it = coll.GetEnumerator();
            bool flag = true;
            while (it.MoveNext())
            {
                flag = predicate(it.Current);
                if (!flag) return false;
            }

            return true;
        }

        public static void Foreach<T>(this IEnumerable<T> coll, Action<T> action)
        {
            Trace.Assert(coll != null, "coll == null");
            Trace.Assert(action != null, "action == null");

            var it = coll.GetEnumerator();
            while (it.MoveNext())
                action(it.Current);
        }

        public static bool Contains<T>(this IEnumerable<T> coll, T item)
        {
            Trace.Assert(coll != null, "coll == null");
            Trace.Assert(item != null, "item == null");

            var it = coll.GetEnumerator();
            while (it.MoveNext())
                if (object.Equals(it.Current, item))
                    return true;

            return false;
        }

        public static IEnumerable<TOutput> ConvertAll<TInput, TOutput>(this IEnumerable<TInput> coll, Converter<TInput, TOutput> converter)
        {
            Trace.Assert(coll != null, "coll == null");
            Trace.Assert(converter != null, "converter == null");

            return from input in coll
                   select converter(input);
        }

        public static bool Exist<T>(this IEnumerable<T> coll, Predicate<T> predicate)
        {
            Trace.Assert(coll != null, "coll == null");
            Trace.Assert(predicate != null, "predicate == null");

            var it = coll.GetEnumerator();
            while (it.MoveNext())
                if (predicate(it.Current))
                    return true;

            return false;
        }


        public static bool In<T>(this T t, IEnumerable<T> c)
        {
            return c.Any(i => i.Equals(t));
        }

       
    }
}
